package com.kaifamiao.jdbc.d0908;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

public class Demo05 {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/kfm";
        String user = "root";
        String password = "";

        MysqlDataSource dataSource = new MysqlDataSource();

        dataSource.setURL(url);
        dataSource.setUser(user);
        dataSource.setPassword(password);

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            // 手动提交事务
            connection.setAutoCommit(false);
            QueryRunner runner = new QueryRunner();

            String sql = "update users set password = ? where id = ?";
            runner.update(connection, sql, "321123", 1);

            int i = 1 / 0;

//            connection.commit();
            // 提交事务
            DbUtils.commitAndClose(connection);
        } catch (Exception e) {
            System.out.println("回滚事务");
            e.printStackTrace();
            try {
                // 回滚事务
                DbUtils.rollback(connection);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }
}
